import { order_state_map, coupon_state_map } from '../../../utils/dataset/db_data'
import drawQrcode from 'weapp-qrcode';

Page({
  data: {
    orderId: '',
    reload: 0,
    couponMap: null,
    orderLastRemark: '',
    // 管理员视图
    adminView: 0,
  },
  onLoad(options) {
    this.setData({ orderId: options.orderId, adminView: options.adminView || 0 });
    this.loadOrderData();
  },
  onShow() {
    if (this.data.reload) {
      this.loadOrderData();
      this.setData({ reload: 0 })
    }
  },
  async loadOrderData() {
    const res = await new Promise(resolve => {
      wx.cloud.callFunction({
        name: 'db_order',
        data: {
          funcName: 'queryOne',
          order_id: this.data.orderId,
        },
        success: (r) => resolve(r.result),
      });
    })
    console.log(res);
    const hh = Array.apply(null, { length: 25 }).map((o, i) => {
      let s = '00' + i;
      return s.substring(s.length - 2);
    });
    const mm = ['00', '30'];
    const timeText = [];
    for (let i = 0; i <= 48; i++) {
      timeText.push(hh[i >> 1] + ':' + mm[i & 1]);
    }
    const order = res.order, couponList = res.coupon_list, orderChangeList = res.order_change_list;
    this.setData({ orderLastRemark: orderChangeList[orderChangeList.length - 1].remark })
    const curTs = new Date().getTime();
    order.left_payment_time = 15 * 60 * 1000 - (curTs - order.created_time);
    order.created_time = new Date(order.created_time).Format()
    order.modified_time = new Date(order.modified_time).Format()
    order.payment_price_text = order.payment_price.toFixed(2);
    order.order_state_text = order_state_map.get(order.order_state);
    order.refund = 0;
    const adminView = this.data.adminView;
    order.court_info = order.sku_list.map((sku, i) => {
      const coupon = couponList.filter(o => o.sku.court_id == sku.court_id && o.sku.rid == sku.rid)[0];
      const hasCoupon = typeof (coupon) !== 'undefined';
      // 管理员不受开场前 3 小时不可退款的限制
      const refund = (hasCoupon) && (coupon.coupon_state == 0)
        && ((coupon.end_time - curTs > 3 * 3600000 ? 1 : 0) || adminView) ? 1 : 0;
      order.refund |= refund;
      return {
        court_name: order.courts.filter(court => court._id == sku.court_id)[0].court_name,
        court_price: order.price_list[i],
        time_text: timeText[sku.rid] + ' ~ ' + timeText[sku.rid + 1],
        coupon_state: hasCoupon ? coupon.coupon_state : -1,
        coupon_state_text: hasCoupon ? coupon_state_map.get(coupon.coupon_state) : '',
        refund,
        coupon_id: hasCoupon ? coupon._id : '',
      }
    })
    order.dateStr = new Date(parseInt(order.appointment_id.substring(order.appointment_id.lastIndexOf('-') + 1) * 1e5)).Format('yyyy-MM-dd');
    order.stadium_info = order.stadium[0];
    this.setData(order);
    this.generateQrcode(order._id);
  },
  onNavigateBack() {
    wx.navigateBack()
  },
  onPay() {
    this.setData({ reload: 1 })
    wx.navigateTo({
      url: `/pages/creator/payment?price=${this.data.payment_price}&stadiumName=${this.data.stadium_name}&dateStr=${this.data.dateStr}&orderId=${this.data.orderId}`,
    })
  },
  generateQrcode(order_id) {
    drawQrcode({
      width: 150,
      height: 150,
      canvasId: 'verifyQrcode',
      foreground: '#1989fa',
      text: 'DGQHqGSRQhqRF_RHQHhyda' + order_id
    })
  },
  async onRefund() {
    const confirm = await new Promise(resolve => {
      wx.showModal({
        title: '确定退款',
        content: '退款操作不可变更',
        success: (r) => resolve(r.confirm)
      })
    })
    if (!confirm) return;
    wx.showLoading({ title: '退款中...', mask: true })
    await new Promise(resolve => {
      wx.cloud.callFunction({
        name: 'db_coupon',
        data: {
          funcName: 'refund',
          order_id: this.data.orderId,
          coupon_ids: this.data.court_info.map(o => o.coupon_id),
          remark: '订单退款【' + this.data.stadium_info.stadium_name + ' ' + this.data.dateStr + '】'
        },
        success: (r) => resolve(r.result),
      });
    })
    wx.hideLoading()
    wx.showToast({
      title: '订单已退款',
      icon: 'none'
    })
    this.loadOrderData();
  },
  async onRefundCoupon(ev) {
    const confirm = await new Promise(resolve => {
      wx.showModal({
        title: '确定退款',
        content: '退款操作不可变更',
        success: (r) => resolve(r.confirm)
      })
    })
    if (!confirm) return;
    wx.showLoading({ title: '退款中...', mask: true })
    await new Promise(resolve => {
      wx.cloud.callFunction({
        name: 'db_coupon',
        data: {
          funcName: 'refund',
          order_id: this.data.orderId,
          coupon_ids: [ev.currentTarget.dataset.coupon_id],
          remark: '订单部分退款【' + this.data.stadium_info.stadium_name + ' ' + this.data.dateStr + '】'
        },
        success: (r) => resolve(r.result),
      });
    })
    wx.hideLoading()
    wx.showToast({
      title: '卡券已退款',
      icon: 'none'
    })
    this.loadOrderData();
  }
})